package com.zhangfei.controller;

import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class AdminController {

    @RequestMapping("/company")
    public String company() {
        return "company: 合肥比亚迪";
    }


    @PreAuthorize("hasAuthority('user')")
    @RequestMapping("/user")
    public String user() {
        String username = getUsername();
        return "username: " + username;
    }



    @RequestMapping("/car")
    public String car() {
        return "car: " + "小米汽车";
    }



    @RequestMapping("/mobile")
    public String mobile() {
        return "mobile: " + "华为手机";
    }



    private String getUsername() {
        // 获取当前登录的用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (!authentication.isAuthenticated()) {
            return null;
        }
        Object principal = authentication.getPrincipal();
        String username = null;
        if (principal instanceof UserDetails) {
            username = ((UserDetails) principal).getUsername();
        } else {
            username = principal.toString();
        }
        return username;
    }

}
